<template>
  <div class="app-container">
    <div class="container_box">
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="12">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="發票編碼" prop="invoiceCode">
                  <el-input disabled v-model="form.invoiceCode" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="來源" prop="invoiceSource">
                  <el-select
                    disabled
                    style="width: 100%"
                    v-model="form.invoiceSource"
                  >
                    <el-option
                      v-for="dict in dict.type.invoice_source"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="標題" prop="invoiceTitle">
                  <el-input disabled v-model="form.invoiceTitle" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="form.invoiceSource == 10">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="報價單編碼" prop="quoteCode">
                  <el-input disabled v-model="form.quoteCode">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 客戶 -->
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="客戶編碼" prop="customerCode">
                  <el-input disabled v-model="form.customerCode"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="客戶名稱" prop="customerName">
                  <el-input disabled v-model="form.customerName" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 銀行 -->
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="入賬銀行賬號" prop="inBankNo">
                  <el-input disabled v-model="form.inBankNo"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="入賬銀行名稱" prop="inBankName">
                  <el-input disabled v-model="form.inBankName" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="有效天數" prop="validDays">
                  <el-input disabled v-model="form.validDays"> </el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="開票時間" prop="invoiceTime">
                  <el-date-picker
                    disabled
                    v-model="form.invoiceTime"
                    type="date"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="稅率" prop="taxRate">
                  <el-input
                    disabled
                    maxlength="4"
                    @change="taxRate_change"
                    oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                    v-model="form.taxRate"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="備註" prop="remark">
                  <el-input
                    disabled
                    @input="$forceUpdate()"
                    v-model="form.remark"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider content-position="center">發票明細信息</el-divider>
            <el-row :gutter="10" class="mb8"> </el-row>
            <el-table
              style="width: 100%"
              :data="bizInvoiceItemList"
              :row-class-name="rowItemIndex"
              :row-key="
                (row) => {
                  return row.index;
                }
              "
              @selection-change="SelectionChange"
              ref="bizCustomerReservationItem"
            >
              <el-table-column
                label="序號"
                align="center"
                prop="index"
                width="50"
              />
              <el-table-column label="發票事項" prop="invoiceItem" width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.invoiceItem" disabled>
                    <el-option
                      v-for="dict in dict.type.business_scope"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="發票金額"
                align="center"
                prop="itemAmount"
              >
                <template slot-scope="scope">
                  <el-input
                    disabled
                    min="0"
                    @change="amountSum(scope.row)"
                    v-model="scope.row.itemAmount"
                  />
                </template>
              </el-table-column>
              <el-table-column label="備註" prop="remark">
                <template slot-scope="scope">
                  <el-input disabled v-model="scope.row.remark" />
                </template>
              </el-table-column>
              <el-table-column label="稅金" align="center" prop="taxAmount">
                <template slot-scope="scope">
                  <span v-if="scope.row.itemAmount">{{
                    scope.row.taxAmount
                  }}</span>
                  <span v-else>0</span>
                </template>
              </el-table-column>
              <el-table-column
                label="發票含稅金額"
                align="center"
                prop="itemTaxAmount"
              >
                <template slot-scope="scope">
                  <span v-if="scope.row.itemAmount">{{
                    scope.row.itemTaxAmount
                  }}</span>
                  <span v-else>0</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <div style="text-align: center; margin-top: 16px">
            <el-button  @click="cancel">返 回</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 選擇客戶  -->
      <el-dialog
        :visible.sync="dialog_if_customer"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px"
        append-to-body
      >
        <single-table
          :selected="selected_customer_id"
          @customer_detail="customer_detail"
          @customer_cancel="customer_cancel"
        >
        </single-table>
      </el-dialog>

      <!-- 選擇入賬銀行 -->
      <el-dialog
        :visible.sync="dialog_if_bank"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px"
        append-to-body
      >
        <bank-table
          :selected="selected_bank_id"
          @out_detail="bank_detail"
          @out_cancel="bank_cancel"
          :type="10"
        >
        </bank-table>
      </el-dialog>
      <!-- 選擇報價單 -->
      <el-dialog
        :visible.sync="dialog_if_quote"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px"
        append-to-body
      >
        <quote-table
          :selected="selected_quote_id"
          @out_detail="quote_detail"
          @out_cancel="quote_cancel"
          :type="10"
        >
        </quote-table>
      </el-dialog>
    </div>
  </div>
</template>
    
    <script>
import { getInvoice, updateInvoice } from "@/api/biz/invoice";
import singleTable from "@/components/biz/singleTable";
import bankTable from "@/components/biz/bankTable";
import quoteTable from "@/components/biz/quoteTable";
export default {
  name: "InvoiceEdit",
  components: { singleTable, bankTable, quoteTable },
  dicts: ["invoice_source", "business_scope"],
  data() {
    return {
      // 表单參數
      form: {
        invoiceSource: "20",
        validDays: 30,
        taxRate: 0,
      },
      // 表单校验
      rules: {},
      // 發票明細表格數据
      bizInvoiceItemList: [],
      checkedList: [],
      // 選擇客戶詳細信息
      dialog_if_customer: false,
      selected_customer_id: "",
      // 選擇銀行詳細信息
      dialog_if_bank: false,
      selected_bank_id: "",
      // 選擇報價單細信息
      dialog_if_quote: false,
      selected_quote_id: "",
    };
  },
  created() {
    if (this.$route.query.id) {
      this.get_detail(this.$route.query.id);
    }
  },
  activated() {
    if (this.$route.query.id) {
      this.get_detail(this.$route.query.id);
    }
  },
  methods: {
    // 選擇 客戶詳細信息----------------------------------
    open_dialog_customer() {
      this.dialog_if_customer = true;
    },
    customer_detail(item) {
      this.selected_customer_id = item.id;

      this.form.customerCode = item.customerCode;
      this.form.customerId = item.id;
      this.form.customerName = item.customerName;
      this.customer_cancel();
    },
    customer_cancel() {
      this.dialog_if_customer = false;
    },

    // 選擇銀行詳細信息----------------------------------
    open_dialog_bank() {
      this.dialog_if_bank = true;
    },
    bank_detail(item) {
      this.selected_bank_id = item.id;
      this.form.inBankId = item.id;
      this.form.inBankNo = item.bankNo;
      this.form.inBankAmount = item.accountName;
      this.form.inBankName = item.bankName;

      this.bank_cancel();
    },
    bank_cancel() {
      this.dialog_if_bank = false;
    },
    //----------------------------------------------------
    // 選擇報價單詳細信息----------------------------------
    open_dialog_quote() {
      this.dialog_if_quote = true;
    },
    quote_detail(item) {
      this.selected_quote_id = item.id;
      this.form.quoteId = item.id;
      this.form.quoteCode = item.quoteCode;
      this.selected_customer_id = item.customerId;
      this.form.customerId = item.customerId;
      this.form.customerName = item.customerName;
      this.form.customerCode = item.customerCode;
      this.form.inBankId = item.inBankId;
      this.selected_bank_id = item.inBankId;
      this.form.inBankNo = item.inBankNo;
      this.form.inBankName = item.inBankName;
      this.form.inBankAmount = item.inBankAccount;
      this.form.validDays = item.validDays;
      this.form.remark = item.remark;
      this.form.taxRate = item.taxRate;
      this.form.taxAmount = item.taxAmount;
      this.form.invoiceAmount = item.quoteAmount;
      this.form.invoiceTaxAmount = item.quoteTaxAmount;
      this.bizInvoiceItemList = [];
      item.bizQuoteItemList.map((ele) => {
        let obj = {
          invoiceItem: ele.itemKey,
          itemAmount: ele.itemAmount,
          itemTaxAmount: ele.itemTaxAmount,
          taxAmount: ele.taxAmount,
          tax: ele.taxRate,
          quantity: ele.quantity,
          uint: ele.uint,
          unitPrice: ele.unitPrice,
          remark: ele.remark ? ele.remark : "",
        };
        this.bizInvoiceItemList.push(obj);
      });
      this.quote_cancel();
    },
    quote_cancel() {
      this.dialog_if_quote = false;
    },
    //----------------------------------------------------

    get_detail(id) {
      getInvoice(id).then((response) => {
        this.selected_quote_id = response.data.quoteId;
        this.selected_customer_id = response.data.customerId;
        this.selected_bank_id = response.data.inBankId;

        this.form.id = response.data.id;
        this.form.invoiceSource = response.data.invoiceSource;
        this.form.invoiceTitle = response.data.invoiceTitle;
        this.form.invoiceCode = response.data.invoiceCode;
        this.form.quoteId = response.data.quoteId;
        this.form.quoteCode = response.data.quoteCode;
        this.form.customerId = response.data.customerId;
        this.form.customerCode = response.data.customerCode;
        this.form.customerName = response.data.customerName;

        this.form.inBankId = response.data.inBankId;
        this.form.inBankNo = response.data.inBankNo;
        this.form.inBankName = response.data.inBankName;
        this.form.inBankAmount = response.data.inBankAmount;

        this.form.validDays = response.data.validDays;

        this.form.taxRate = response.data.taxRate ? response.data.taxRate : "0";

        this.form.taxAmount = response.data.taxAmount;
        this.form.invoiceAmount = response.data.invoiceAmount;
        this.form.invoiceTaxAmount = response.data.invoiceTaxAmount;

        this.form.invoiceTime = response.data.invoiceTime;
        this.form.remark = response.data.remark;
        this.bizInvoiceItemList = [];
        response.data.bizInvoiceItemList.map((item) => {
          let obj = {
            invoiceItem: item.invoiceItem,
            itemAmount: item.itemAmount,
            itemTaxAmount: item.itemTaxAmount,
            taxAmount: item.taxAmount,
            tax: item.tax + "",
            quantity: item.quantity + "",
            uint: item.uint,
            unitPrice: item.unitPrice,
            remark: item.remark ? item.remark : "",
          };
          this.bizInvoiceItemList.push(obj);
        });
      });
    },

    /** 提交按钮 */
    submitForm(type) {
      console.log(this.form);
      console.log(this.bizInvoiceItemList);
      this.form.taxAmount = 0; //稅金
      this.form.invoiceAmount = 0; //報價金額
      this.form.invoiceTaxAmount = 0; // 含稅報價
      this.bizInvoiceItemList.map((item) => {
        item.unitPrice = item.itemAmount;
        this.form.invoiceAmount += item.itemAmount - 0;
        this.form.taxAmount += item.taxAmount - 0;
        this.form.invoiceTaxAmount += item.itemTaxAmount - 0;
      });
      // (scope.row.itemAmount * form.taxRate).toFixed(2)
      this.form.bizInvoiceItemList = this.bizInvoiceItemList;
      this.form.invoiceStatus = type;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateInvoice(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.$tab.closePage().then(() => {
              // 执行結束的逻辑
              const obj = { path: "/invoice/invoice", name: "Invoice" };
              this.$tab.refreshPage(obj);
            });
          });
        }
      });
    },
    cancel() {
      this.$tab.closePage().then(() => {
        // 执行結束的逻辑
        const obj = { path: "/invoice/invoice", name: "Invoice" };
        this.$tab.refreshPage(obj);
      });
    },
    /** 复选框选中數据 */
    SelectionChange(selection) {
      this.checkedList = selection.map((item) => item.index);
    },
    /** 發票明細序號 */
    rowItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 發票明細添加按钮操作 */
    handleAddBizInvoiceItem() {
      let obj = {};
      obj.invoiceItem = "";
      obj.itemAmount = "";
      obj.taxAmount = "";
      obj.itemTaxAmount = "";
      obj.tax = this.form.taxRate;
      obj.quantity = 1;
      obj.uint = "個";
      obj.unitPrice = "";
      obj.remark = "";
      this.bizInvoiceItemList.push(obj);
    },
    /** 發票明細删除按钮操作 */
    handleDeleteBizInvoiceItem() {
      if (this.checkedList.length == 0) {
        this.$modal.msgError("請先選擇要删除的發票明細數据");
      } else {
        const bizInvoiceItemList = this.bizInvoiceItemList;
        const checkedList = this.checkedList;
        this.bizInvoiceItemList = bizInvoiceItemList.filter(function (item) {
          return checkedList.indexOf(item.index) == -1;
        });
      }
    },
    // 計算金額
    amountSum(item) {
      this.bizInvoiceItemList[item.index - 1].tax = this.form.taxRate;
      this.bizInvoiceItemList[item.index - 1].taxAmount = this.computeTaxAmount(
        this.bizInvoiceItemList[item.index - 1].itemAmount,
        this.form.taxRate
      );
      this.bizInvoiceItemList[item.index - 1].itemTaxAmount =
        this.computeItemTaxAmount(
          this.bizInvoiceItemList[item.index - 1].itemAmount,
          this.form.taxRate
        );
      this.$forceUpdate();
      this.bizInvoiceItemList.splice(1, 0);
      console.log(this.bizInvoiceItemList);
    },
    computeTaxAmount(itemAmount, taxRate) {
      return (itemAmount * taxRate).toFixed(2);
    },
    computeItemTaxAmount(itemAmount, taxRate) {
      return (itemAmount * (1 + (taxRate - 0))).toFixed(2);
    },
    // 稅率變化
    taxRate_change() {
      this.bizInvoiceItemList.map((item) => {
        item.tax = this.form.taxRate;
        item.taxAmount = this.computeTaxAmount(
          item.itemAmount,
          this.form.taxRate
        );
        item.itemTaxAmount = this.computeItemTaxAmount(
          item.itemAmount,
          this.form.taxRate
        );
      });
      console.log(this.bizInvoiceItemList);
      this.$forceUpdate();
      this.bizInvoiceItemList.splice(1, 0);
    },
  },
};
</script>
  <style  >
.signType thead .el-table-column--selection .cell {
  display: none;
}
.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
    